<template>
  <Page :title='dictName' @gesture='onGesture' :on-page-back='onPageBack'>
    <template #content>
      <div class='w-full h-full p-20px box-border'>
        <div class='dictDetail box-border flex flex-col'>
          <div class='title' v-if='dictId==1 || dictId==5'>
            <span class='title-w'>{{ word | title(dictId) }}</span>
            <img class='title-icon' src='@/assets/icons/audio.png' mode='' @click='onPlayAudio(word)' v-show="audioUrl" />
          </div>
          <div id='definition'>{{ word | definition(dictId) }}</div>
          <div id='word_detail' v-show="dictId!=5"></div>
        </div>
      </div>
    </template>
  </Page>
</template>
<script>
import Page from '@/components/page/index.vue'
import { dictMap } from '@/views/dict/index'
import { mapGetters } from 'vuex'

export default {
  filters: {
    title(word = '', dictId) {
      try {
        switch (dictId) {
          case '5':
            if (word.match(/[\w\W]*【[\w\W]*】/)) {
              const wordCn = word.slice(word.lastIndexOf('【'))
              const wordJp = word.replace(wordCn, '')
              return wordJp
            } else {
              return word
            }
          default:
            return word
        }
      } catch {
        return word
      }
    },
    definition(word = '', dictId) {
      try {
        switch (dictId) {
          case '5':
            if (word.match(/[\w\W]*【[\w\W]*】/)) {
              const wordCn = word.slice(word.lastIndexOf('【')).replace('【', '').replace('】', '')
              return `中文：${wordCn}`
            } else {
              return ''
            }
          default:
            return ''
        }
      } catch {
        return ''
      }
    }
  },
  components: { Page },
  data() {
    return {
      dictId: 1,
      word: '',
      mDict: null,
      audioUrl: ''
    }
  },
  computed: {
    dictName() {
      return dictMap[this.$route.query.id]
    },
    ...mapGetters(['myDict'])
  },
  methods: {
    init() {
      let id = this.$route.query.id
      if (id) {
        this.dictId = id
      }
      let word = this.$route.query.word
      this.searchWord(word)
    },
    searchWord(word) {
      console.log('搜索单词',word)
      const that = this
      const loading = this.$loading({
        lock: true,
        text: '加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)'
      })
      try {
        const callback = (result) => {
          console.log('搜索结果', result)
          loading.close()
          if (result) {
            that.word = word
            result = result.replace(/\。\。/g, '\'')
            that.setWordInfoHtml(result)
          } else {
            that.$message.error(`查询失败.`)
          }
        }
        const callBackName = `fn${new Date().getTime()}`
        window.android_call[callBackName] = callback.bind(this)
        word = word.toLowerCase()
        switch (this.dictId) {
          case '1':
            android.yhsearch(word, callBackName)
            break
          case '2':
            android.hysearch(word, callBackName)
            break
          case '3':
            android.xdhysearch(word, callBackName)
            break
          case '4':
            android.gdhysearch(word, callBackName)
            break
          case '5':
            android.jpsearch(word, callBackName)
            break
        }
      } catch (e) {
        loading.close()
        this.$message.error(`查询失败.`)
      }
    },
    async setWordInfoHtml(html) {
      console.log(html)
      try {

        const that = this
        const parser = new DOMParser()
        const doc = parser.parseFromString(html, 'text/html')
        const body = doc.body
        const wordDetailRef = document.getElementById('word_detail')
        wordDetailRef.innerHTML = ''
        console.log(doc)

        const newDiv = document.createElement('div')
        newDiv.innerHTML = body.innerHTML
        wordDetailRef.appendChild(newDiv)

        wordDetailRef.addEventListener('click', function(e) {
          if (e.target.tagName === 'A') {
            e.preventDefault()
            const href = e.target.getAttribute('href')
            if (href && href.substring(0, 8) === 'entry://') {
              let word = href.substring(8)
              if (word.charAt(0) !== '#') {
                word = word.replace(/(^[/\\])|([/]$)/, '')
                const searchWord = word.match(/^([^#]*)/)
                that.searchWord(searchWord ? searchWord[1] : word)
              } else {
                let currentUrl = location.href
                location.href = word
                history.replaceState(null, null, currentUrl)
              }
            }
          }
        })
        const soundLink = Array.from(document.querySelectorAll(that.dictId == 1 ? '#word_detail a[type="sound"]' : '#word_detail a[href^="sound://SPX/"]'))[0]
        if (soundLink) {
          const href = soundLink.getAttribute('href')
          if (href) {
            const audioUrl = href.split('/').pop().replace('.spx', '')
            if (audioUrl) {
              this.audioUrl = audioUrl
            }
          }
        }
      } catch (e) {
        console.log(e)
      }
    },
    onGesture() {
      console.log('onGesture')
    },
    onPageBack() {
      this.$router.back()
    },
    onPlayAudio() {
      const that = this
      try {
        const dictFileName = that.dictId == 1 ? 'yh.db' : 'jpmp3.db'
        const callback = (result) => {
          if (result == 1) {
            android.play(that.audioUrl + '', that.dictId == 1 ? 1 : 0)
          } else {
            that.$message.warning('资源加载中...')
          }
        }
        const callBackName = `fn${new Date().getTime()}`
        window.android_call[callBackName] = callback.bind(this)
        android.fileIsExist(dictFileName, callBackName)
      } catch (e) {
        this.$message.error('加载文件失败')
      }
    }
  },
  mounted() {
    this.init()
  }
}
</script>
<style scoped lang='scss'>
.dictDetail {
  font-size: 16px;
  padding: 20px;
  background: #fff;
  border-radius: 16px;
  height: 100%;
  overflow-y: auto;

  .title {
    display: flex;
    align-items: flex-end;
  }

  .title-w {
    font-size: 40px;
    font-weight: 600;
    color: #409EFF;
    display: inline-block;
  }

  .title-icon {
    width: 20px;
    height: 20px;
    margin-left: 10px;
  }

  #definition {
    font-size: 20px;
  }

  #word_detail {
    font-size: 20px;
  }

  // 汉英词典
  /deep/ #word_detail {
    img {
      display: none;
    }

    .infl {
      display: block;
    }

    .para {
      display: block;
      margin-left: 20px;
    }

    .z_phon-us {
      display: none;
    }

    .id-g {
      display: block;
    }
  }

  /deep/ .top-g {
    .h {
      display: none;
    }
  }

  /deep/ .return-phrase {
    font-size: 40px;
    font-weight: 600;
    color: #51c3ff;
    display: inline-block;
  }

  /deep/ .phone {
    font-size: 20px;
    color: #858585;
    margin-left: 10px;
    display: inline-block;
  }

  /deep/ .trs {
    display: block;
    .pos {
      font-size: 24px;
      margin-left: 20px;
      margin-top: 10px;
      color: #79bbff;
    }

    .tr {
      margin-left: 20px;
      display: block;
      margin-bottom: 10px;
      /deep/ .exam > .i{
        display: block;
        color: #73767a;
      }
    }
  }
  /deep/ .phr{
    display: block;
  }


  //英汉词典样式
  /deep/ .h {
    @extend .return-phrase;
  }

  /deep/ .pos-g {
    display: block;
    font-size: 20px;
  }

  /deep/ .entry {
    line-height: 35px;
  }

  /deep/ .p-g {
    margin-left: 15px;
    display: block;
  }

  /deep/ .n-g {
    display: block;
  }

  /deep/ .x-g {
    display: block;
    margin-left: 20px;
  }

  /deep/ #word_detail > p:first-child {
    display: none;
  }

  /deep/ .pracpron {
    display: none;
  }

  // 现代汉语词典样式
  // 古汉语词典
  /deep/ #titleText {
    @extend .return-phrase;
  }

  /deep/ #titlePY {
    @extend .phone;
  }
  /deep/ #pageFrist{
    display: none;
  }
  /deep/ #pagePre{
    display: none;
  }
  /deep/ #pageNext{
    display: none;
  }
  /deep/ #pageLast{
    display: none;
  }
}
</style>
